package bll

import (
	"encoding/json"
	"fmt"
	"net/http"

	"jgt-wallet/src/gopay/unionpay"
	payUtil "jgt-wallet/src/gopay/util"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/util"
)

// 支付宝APP
type UnionpayB2B struct {
	OrderBll *Order `inject:""`
}

// Pay 支付
func (a *UnionpayB2B) Pay(key string, params *schema.UnionpayB2BParams) (string, error) {
	var (
		client *unionpay.B2bClient
		old    *schema.OrderQueryResult
		order  = new(schema.Order)
		charge = new(unionpay.Charge)
		err    error
		html   string
	)

	//检验订单可支付性
	old, err = a.OrderBll.GetOrderResult(params.OrderID)
	if err != nil {
		return "", err
	}
	if old.Result == schema.RESULT_SUCCESS {
		return "", fmt.Errorf("订单已支付")
	} else if old.Result == schema.RESULT_ERROR {
		return "", fmt.Errorf("订单异常,请联系客服")
	}

	order.PayType = schema.PAY_TYPE_UNIONPAY_B2B
	order.Client = key

	order.RecordID = util.GenerateRecordID()
	order.OrderID = params.OrderID
	order.Price = params.Price
	order.Des = params.Describe
	order.Tag = params.Tag

	client = unionpay.GetB2bClient(key)
	if client == nil {
		return "", fmt.Errorf("未找到指定支付宝APP客户端")
	}

	//支付
	charge.MoneyFee = params.Price    //支付额(分)
	charge.Describe = params.Describe //支付描述
	charge.TradeNum = order.RecordID  //交易号
	charge.CallbackURL = params.Url   //回调地址

	html, err = client.Pay(charge)
	if err != nil {
		return "", err
	}

	order.PayData = html
	err = a.OrderBll.CreateOrder(order)
	if err != nil {
		return "", err
	}

	return html, nil
}

// CallBack 异步回调
func (a *UnionpayB2B) CallBack(key string, w http.ResponseWriter, r *http.Request) error {
	return nil
}

// QueryOrderResult 查询订单支付结果
func (a *UnionpayB2B) QueryOrderResult(recordId string) error {
	var (
		data   *unionpay.QueryResult
		client *unionpay.B2bClient
		order  *schema.Order
		item   = new(schema.Order)
		err    error
	)

	order, err = a.OrderBll.GetOrder(recordId)
	if err != nil {
		return err
	}
	if order.PayType != schema.PAY_TYPE_UNIONPAY_B2B {
		return fmt.Errorf("支付方式错误")
	}
	client = unionpay.GetB2bClient(order.Client)
	if client == nil {
		return fmt.Errorf("找不到指定客户端")
	}
	item.RecordID = order.RecordID

	data, err = client.QueryOrder(recordId)
	bs, _ := json.Marshal(data)
	item.QueryData = string(bs)
	item.TradeID = data.OrderId
	if data.RespCode == "00" {
		item.Status = schema.ORDER_STATUS_SUCCESS
		item.RealPrice = payUtil.ParseMoneyFen(data.TxnAmt)

	} else if data.RespCode == "03" || data.RespCode == "04" || data.RespCode == "05" {
		item.Status = schema.ORDER_STATUS_ERROR
	} else {
		item.Status = schema.ORDER_STATUS_FAIL

	}

	return a.OrderBll.UpdateOrder(item)
}
